import querystring from "querystring";
const methods = {
  json() {
    return function (req, res, next) {
      console.log(req.headers["content-type"]);
      if (req.headers["content-type"] === "application/json") {
        const arr = [];
        req.on("data", function (chunk) {
          arr.push(chunk);
        });
        req.on("end", function () {
          req.body = JSON.parse(Buffer.concat(arr).toString());
          next();
        });
      } else {
        next();
      }
    };
  },
  urlencoded() {
    return function (req, res, next) {
      if (req.headers["content-type"] === "application/x-www-form-urlencoded") {
        const arr = [];
        req.on("data", function (chunk) {
          arr.push(chunk);
        });
        req.on("end", function () {
          req.body = querystring.parse(Buffer.concat(arr).toString());
          next();
        });
      } else {
        next();
      }
    };
  },
};

const bodyParser = function (express) {
  Object.keys(methods).forEach((type) => {
    express[type] = methods[type];
  });
};

export default bodyParser;
